<?php
namespace app\shouyin\admin;
use app\system\admin\Admin;
use app\shouyin\model\UserBalance as UserBalanceModel;
use app\shouyin\model\UserBalanceLog as UserBalanceLogModel;
use app\finance\model\Account as AccountModel;
use app\user\model\User as UserModel;
use app\system\model\systemUser as systemUserModel;
use think\Db;
class Recharge extends Admin
{
    protected $hisiModel = 'UserBalance';//模型名称[通用添加、修改专用]
    protected $hisiTable = '';//表名称[通用添加、修改专用]
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名
    protected function initialize()
    {
        parent::initialize();
        $admin = systemUserModel::get(ADMIN_ID);

        $this->assign('admin_type',$admin['type']);
        if ($this->request->action() != 'index' && !$this->request->isPost()) {
            $where = [];

            $where['shop_id'] = session('shop_id');

            // 会员
            $users = UserModel::getSelect(UserModel::all());
            $this->assign('users', $users);
            $accounts = AccountModel::getSelect(AccountModel::where('id','<>',0)->all());
            $this->assign('accounts', $accounts);
            // 顾问
            $admins = systemUserModel::where($where)->all();
            $advisers = [];
            $technician = [];
            foreach ($admins as $key => $value) {
                if($value['type'] == '顾问'){
                    $advisers[] = $value;
                }else if($value['type'] == '美容师'){
                    $technician[] = $value;
                }
            }

            $this->assign('advisers', systemUserModel::getSelect($advisers));
            $this->assign('technicians', systemUserModel::where('type', 7)->where('shop_id',session('shop_id'))->field('id as value,nick as name')->all());

        }
    }
    public function index()
    {
        if ($this->request->isAjax()) {
            $where      = [];
            $where['shop_id'] = session('shop_id');
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $data['data'] = UserBalanceModel::where($where)
                            ->field('*,user_id as user_id_text,shop_id as shop_id_text, finance_id as finance_id_text, adviser_id as adviser_id_text,technician_id as technician_text, cashier_id as cashier_id_text,account_id as account_id_text')
                            ->page($page)
                            ->limit($limit)
                            ->order('id desc')
                            ->select();
                            // halt($data);
            $data['count'] = UserBalanceModel::where($where)->count('id');
            $data['code'] = 0;
            return json($data);
        }
        return $this->fetch();
    }
    public function add()
    {
        if ($this->request->isPost()) {

            $postData = $this->request->post();
            $meirongshi = Db::name('system_user')->where('id','in',$postData['technician_id'])->column('id,nick');

            Db::startTrans();
            try {
                // echo 1;
                UserBalanceModel::create($postData);
                $UserBalanceLogModel = new UserBalanceLogModel;
                $log = [
                    'user_id' => $postData['user_id'],
                    'type' => 1,
                    'price' => $postData['price1'],
                    'sn' => $postData['sn'],
                ];
                // 顾问
                $jixiao = [];
                $jixiao[] = [
                    'admin_id' => $postData['adviser_id'],
                    'user_id' => $postData['user_id'],
                    'project' => '会员卡充值--充'.$postData['price1'] . '赠' . $postData['price2'],
                    'num' => 1,
                    'price' => $postData['price1'],
                    'shougong' => 0,
                    'settlement' => '现金',
                    'shop_id' => $postData['shop_id'],
                    'admin_type' => '顾问',
                    'proportion' => 0,
                    'createtime' => date('Y-m-d H:i:s',time()),
                    'sn' => $postData['sn'],
                ];
                foreach ($meirongshi as $key => $value) {
                    $jixiao[] = [
                        'admin_id' => $key,
                        'user_id' => $postData['user_id'],
                        'project' => '会员卡充值--充'.$postData['price1'] . '赠' . $postData['price2'],
                        'num' => 1,
                        // 'price' => $postData['price1'],
                        'price' => round(($postData['price1'] / count($meirongshi)),2),
                        'shougong' => 0,
                        'settlement' => '现金',
                        'shop_id' => $postData['shop_id'],
                        'admin_type' => '美容师',
                        'proportion' => 0,
                        'createtime' => date('Y-m-d H:i:s',time()),
                        'sn' => $postData['sn'],
                    ];
                }
                if(count($jixiao) > 0){
                    Db::name('achievements')->insertAll($jixiao);
                }

                if($postData['price2'] != 0.00){
                    $log2 = [
                        'user_id' => $postData['user_id'],
                        'type' => 1,
                        'price' => $postData['price2'],
                        'sn' => $postData['sn'],
                        'is_give' => 2,
                        'sn' => $postData['sn'],
                    ];
                    // echo 2;
                    $UserBalanceLogModel->create($log2);
                }
                // echo 3;
                $UserBalanceLogModel->create($log);
                if($postData['price1'] > 0){
                    $sys = [
                        'sn' => $postData['sn'],
                        'type' => 3,
                        'account_id' => $postData['account_id'],
                        'shop_id' => $postData['shop_id'],
                        'price' => $postData['price1'],
                        'createtime' => time(),
                        'updatetime' => time(),
                        'is_effective' => 1,
                        'user_id' => $postData['user_id'],
                        'cate' => 1,
                        ];
                        // echo 4;
                    Db::name('system_balance_log')->insert($sys);
                }

                // echo 5;
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('保存成功', '');

        }

        $template = $this->request->param('template', 'form');

        return $this->fetch($template);
    }

   public function edit()
    {
        if ($this->request->isPost()) {// 数据验证

            $postData = $this->request->post();
        }

        $where = [];

        $db = Db::name('user_balance');
        $pk = $db->getPk();
        $id = $this->request->param($pk);

        $where[]= [$pk, '=', $id];
        $where  = $this->getRightWhere($where);

        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                Db::name('user_balance')->where($where)->update($postData);

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('保存成功', '');
        }

        $formData = $db->where($where)->find();



        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }

        // halt($formData);


        $template = $this->request->param('template', 'form');
        if(!is_empty($this->request->param('xx')) && $this->request->param('xx') == 2){
            $formData['user_name'] = Db::name('user')->where('id',$formData['user_id'])->value('nick');
            // halt($formData  );
            $formData['technician_name'] = implode(',', Db::name('system_user')->where('id','in',$formData['technician_id'])->column('nick'));
            $formData['adviser_name'] = Db::name('system_user')->where('id',$formData['adviser_id'])->value('nick');
            $formData['account_name'] = Db::name('account')->where('id',$formData['account_id'])->value('name');
            $this->view->engine->layout(false);
            $this->assign('formData', $formData);
            return $this->fetch('dayin');
        }
        $formData['technician_id'] = Db::name('system_user')->where('id','in',$formData['technician_id'])->field('id as value, nick as name')->select();
        $this->assign('formData', $formData);
        return $this->fetch($template);
    }


}
